package com.zerosoft.shuguang.service;

import lombok.Data;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.UUID;

@Data
public class MqttSerialClient {
    @Value("${mqtt.serverTopic}")
    private String serverTopic;
    @Value("${mqtt.defaultTopic}")
    private String defaultTopic;
    @Value("${mqtt.hostUrl}")
    private String hostUrl;
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.client-id}")
    private String clientId;
    @Value("${mqtt.cleanSession}")
    private boolean cleanSession;
    @Value("${mqtt.reconnect}")
    private boolean reconnect;
    @Value("${mqtt.timeout}")
    private int timeout;
    @Value("${mqtt.keepAlive}")
    private int keepAlive;
    @Value("${mqtt.qos}")
    private int qos;
    @Value("${mqtt.isOpen}")
    private boolean isOpen;

    private Environment ev;
    public MqttSerialClient()
    {
//        this.ev = getBean(Environment.class);
        hostUrl = "tcp://121.31.211.219:1883";
        username = "";
        password = "";
        timeout = 200;
        keepAlive = 200;
        serverTopic = "shuguang";
    }

    private static final Logger logger       = LoggerFactory.getLogger(MqttSerialClient.class);
    public MqttClient connect() {
        MqttClient client = null;
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            client = new MqttClient(hostUrl, uuid, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);
            options.setCleanSession(false);
            options.setAutomaticReconnect(false);
            // 设置回调
//            client.setCallback(
//                    new MqttCallbackExtended(){
//                        @Override
//                        public void connectionLost(Throwable throwable) {
//                            logger.info("连接断开，可以重连");
//                        }
//
//                        @Override
//                        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
//                            logger.info("【接收消息主题】: " + s);
//                            logger.info("【接收消息Qos】: " + mqttMessage.getQos());
//                            logger.info("【接收消息内容】: " + new String(mqttMessage.getPayload()));
//                        }
//
//                        @Override
//                        public void deliveryComplete(IMqttDeliveryToken token) {
//                            String[] topics = token.getTopics();
//                            for (String topic : topics) {
//                                logger.info("向主题【" + topic + "】发送消息成功！");
//                            }
//                            try {
//                                MqttMessage message = token.getMessage();
//                                byte[] payload = message.getPayload();
//                                String s = new String(payload, "UTF-8");
//                                logger.info("【消息内容】:" + s);
//                            } catch (Exception e) {
//                                logger.error("MqttSendCallBack deliveryComplete error,message:{}", e.getMessage());
//                                e.printStackTrace();
//                            }
//                        }
//                        @Override
//                        public void connectComplete(boolean reconnect, String serverURI) {
//                            logger.info("MqttSendClient connectComplete,reconnect:{},serverURI:{}", reconnect, serverURI);
//                            logger.info("============================= 客户端【" + MqttAcceptClient.client.getClientId() + "】连接成功！=============================");
//                        }
//                    }
//            );
            client.connect(options);
        } catch (Exception e) {
            logger.error("MqttSendClient connect error,message:{}", e.getMessage());
            e.printStackTrace();
        }
        return client;
    }
    public void publish(boolean retained, String topic, String content) {
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        message.setRetained(retained);
//        message.setPayload(content.getBytes());
        MqttDeliveryToken token;
        MqttClient mqttClient = connect();
        try {
            mqttClient.publish(serverTopic+topic, message);
        } catch (MqttException e) {
            logger.error("MqttSendClient publish error,message:{}", e.getMessage());
            e.printStackTrace();
        } finally {
            disconnect(mqttClient);
            close(mqttClient);
        }
    }
    /**
     * 关闭连接
     *
     * @param mqttClient
     */
    public static void disconnect(MqttClient mqttClient) {
        try {
            if (mqttClient != null)
                mqttClient.disconnect();
        } catch (MqttException e) {
            logger.error("MqttSendClient disconnect error,message:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     *
     * @param mqttClient
     */
    public static void close(MqttClient mqttClient) {
        try {
            if (mqttClient != null)
                mqttClient.close();
        } catch (MqttException e) {
            logger.error("MqttSendClient close error,message:{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
